import 'package:dio/dio.dart';
import 'package:encrypt/encrypt.dart' as encrypt;
import 'dart:convert';

class SecureCommunicationInterceptor extends Interceptor {
  static const _aesKey = '12345678901234567890123456789012'; // 32字节AES密钥
  static const _aesIv = '1234567890123456'; // 16字节IV
  
  final _encrypter = encrypt.Encrypter(
    encrypt.AES(
      encrypt.Key.fromUtf8(_aesKey),
      mode: encrypt.AESMode.cbc,
    ),
  );
  
  final _iv = encrypt.IV.fromUtf8(_aesIv);

  @override
  void onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) {
    try {
      print('🔍 Request path: ${options.path}');
      print('🔍 Should encrypt: ${options.path.startsWith('/api/')}');
      
      // 只对 /api/ 路径下的请求进行加密
      if (options.path.startsWith('/api/') && options.data != null && options.data is! FormData) {
        print('🔐 Encrypting request data...');
        final jsonData = options.data is String 
            ? options.data 
            : jsonEncode(options.data);
        
        print('📤 Original data: $jsonData');
        
        final encrypted = _encrypter.encrypt(jsonData, iv: _iv);
        final encryptedData = {'encrypted': encrypted.base64};
        
        print('🔐 Encrypted data: $encryptedData');
        
        options.data = encryptedData;
        options.headers['X-Encrypted'] = 'true';
        options.headers['Content-Type'] = 'application/json';
        
        print('✅ Request encrypted successfully');
      } else {
        print('⚪ Request not encrypted (path: ${options.path})');
      }
      
      handler.next(options);
    } catch (e) {
      print('❌ Encryption error: $e');
      handler.reject(DioException(
        requestOptions: options,
        error: 'Encryption failed: $e',
      ));
    }
  }

  @override
  void onResponse(
    Response response,
    ResponseInterceptorHandler handler,
  ) {
    try {
      print('📥 Response status: ${response.statusCode}');
      print('📥 Response headers: ${response.headers}');
      print('📥 Response data type: ${response.data.runtimeType}');
      print('📥 Response data: ${response.data}');
      
      if (response.headers.value('X-Encrypted') == 'true') {
        print('🔓 Decrypting response...');
        final data = response.data;
        if (data != null && data is Map<String, dynamic>) {
          final encrypted = data['encrypted'];
          if (encrypted != null && encrypted is String) {
            print('🔓 Encrypted response data: $encrypted');
            try {
              final decrypted = _encrypter.decrypt64(encrypted, iv: _iv);
              print('🔓 Decrypted response data: $decrypted');
              
              // 解析JSON字符串为Map
              final decryptedMap = jsonDecode(decrypted);
              print('🔓 Parsed decrypted data: $decryptedMap');
              
              // 确保返回的是Map<String, dynamic>
              if (decryptedMap is Map<String, dynamic>) {
                response.data = decryptedMap;
                print('✅ Response decrypted successfully: ${response.data}');
              } else {
                print('⚠️ Decrypted data is not a Map, wrapping it');
                response.data = {'data': decryptedMap};
              }
            } catch (decryptError) {
              print('❌ Decryption error: $decryptError');
              response.data = {
                'error': 'Failed to decrypt response',
                'details': decryptError.toString()
              };
            }
          } else {
            print('⚠️ No encrypted field in response data or invalid type');
            response.data = {
              'error': 'Invalid encrypted response format',
              'original_data': data
            };
          }
        } else {
          print('⚠️ Response data is not a Map or is null');
          response.data = {
            'error': 'Response data format error',
            'original_data': data
          };
        }
      } else {
        print('⚪ Response not encrypted');
        // 确保非加密响应也不为null
        if (response.data == null) {
          response.data = <String, dynamic>{};
        }
      }
      
      handler.next(response);
    } catch (e) {
      print('❌ Response processing error: $e');
      print('❌ Error stack trace: ${StackTrace.current}');
      
      // 创建一个错误响应而不是拒绝请求
      response.data = {
        'error': 'Response processing failed',
        'details': e.toString()
      };
      
      handler.next(response);
    }
  }
}
